package com.wh.wisdomsite.xbox.server.controller.wo;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.wo.workerInfo.GetWorkerListOut;
import com.wh.wisdomsite.xbox.pojo.wo.workerInfo.WorkerDetail;
import com.wh.wisdomsite.xbox.pojo.wo.workerInfo.WorkerInfoIn;
import com.wh.wisdomsite.xbox.pojo.wo.workerInfo.WorkerInfoOut;
import com.wh.wisdomsite.xbox.pr.entity.Project;
import com.wh.wisdomsite.xbox.pr.service.IProjectService;
import com.wh.wisdomsite.xbox.server.util.DateUtils;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.utils.Const;
import com.wh.wisdomsite.xbox.utils.IDCardUtils;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.server.connToserver_HttpClientClose;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 农名工人员信息controller
 * @author 刘旭
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.server.controller.wo
 * @date 2018年09月17日 9:27
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@Controller
@RequestMapping(value = "/workerInfo")
public class WorkerInfoController {
    private static final Log logger = LogFactory.getLog(WorkerInfoController.class);

    @Autowired
    private IProjectService iProjectService;

    /**
     * 补卡需要用到的人员部分数据
     */
    private Map<String,Map<String,String>> repairInfoMap = new HashMap<>();

    /**
     * 跳转到农名工人员信息
     *
     * @return
     */
    @RequiresPermissions("rules:wo_workerInfo_page")
    @RequestMapping(value = "/index.do", method = RequestMethod.GET)
    public String index() {
        return "wo/workerInfo/workerInfoList";
    }

    /**
     * 获取人员信息列表
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:wo_workerInfo_find")
    @RequestMapping(value = "/workerInfoList.do")
    public void workerInfoList(HttpServletResponse response, WorkerInfoIn in) {
        logger.info("加载农名工人员信息列表-->>开始");
        try {
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<Project> page = new Page<Project>();
            page.setCurrent(1);
            page.setSize(Integer.MAX_VALUE);
            EntityWrapper<Project> ewProject = new EntityWrapper<Project>();
            ewProject.setEntity(new Project());
            //若不是超级管理员则根据用户权限添加查询条件
            if (!UserUtils.isSysAdmin()) {
                ewProject = UserUtils.setEntityWrapper(ewProject, "c1", "o1", "p");
            }
            ewProject.groupBy("p.prId");
            Page<Map<String, Object>> projectPage = iProjectService.getMapsPage(page, ewProject);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            String projectIds = "";
            int total = 0;
            //将项目id和项目名称存入projectMap
            Map<String,String> projectMap = new HashMap<String,String>();
            if (projectPage.getRecords().size() > 0) {
                for (Map<String, Object> project : projectPage.getRecords()) {
                    String projectId = (String) project.get("prId");
                    String projectName = (String) project.get("prName");
                    projectIds = projectIds + projectId + ",";
                    projectMap.put(projectId,projectName);
                }
            }
            if (StringUtils.isNotEmpty(projectIds)) {
                String projectIdsRel = projectIds.substring(0, projectIds.length() - 1);
                //接口查询条件
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageNumber", String.valueOf(in.getPage()));
                map.put("pageSize", String.valueOf(in.getRows()));
                map.put("projectIds", projectIdsRel);
                if(StringUtils.isNotEmpty(in.getProjectId())){
                    map.put("projectIds", in.getProjectId());
                }
                if(StringUtils.isNotEmpty(in.getUserName())){
                    map.put("userName", in.getUserName());
                }
                if(StringUtils.isNotEmpty(in.getWorkName())){
                    map.put("workName", in.getWorkName());
                }
                //接口查询结果
                String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_PERSONPAGEURL, map);
                if(result.contains("idCard")){
                    result = result.replaceAll("Work","work").replaceAll("Group","group").replaceAll("null","\"\"");
                }
                //对象中存在集合的需要通过map注明集合的类型，否则会报错
                Map classMap = new HashMap();
                classMap.put("persons",WorkerInfoOut.class);
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                GetWorkerListOut workers = (GetWorkerListOut)net.sf.json.JSONObject.toBean(jsonObject, GetWorkerListOut.class,classMap);
                //获取总条数
                total = workers.getPersonObj().getTotal();
                //农名工信息集合
                List<WorkerInfoOut> workerList = workers.getPersonObj().getPersons();
                for(WorkerInfoOut worker : workerList){
                    JSONObject jsonObj = new JSONObject(worker);
                    String idCard = worker.getIdCard();
                    // 获取年龄
                    Integer age = null;
                    if(idCard.length() > 15){
                        Map<String, Object> mapCard = IDCardUtils.getCarInfo(idCard);
                        age = (Integer) mapCard.get("age");
                    }else{
                        Map<String, Object> mapCard = IDCardUtils.getCarInfo15W(idCard);
                        age = (Integer) mapCard.get("age");
                    }
                    // 获取项目名称
                    String projectId = worker.getProjectId();
                    String projectName = projectMap.get(projectId);
                    jsonObj.put("age",age);
                    jsonObj.put("projectName",projectName);
                    array.put(jsonObj);
                }
            }
            json.put("total", total);
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取人员信息-->>Exception " + e.getMessage());
        }
    }

    /**
     * 获取人员具体信息
     * @param request
     * @param idCard
     * @param projectName
     * @return
     */
    @RequestMapping(value = "/workerInfoDesc.do")
    public String workerInfoDesc(HttpServletRequest request,String idCard,String projectName,String projectId){
        logger.info("加载农名工人员信息列表-->>开始");
        //劳务人员详情
        WorkerDetail workerDetail = new WorkerDetail();
        Integer age = null;
        String createDate = null;
        Integer effectiveTime = null;
        try{
            if(StringUtils.isNotEmpty(idCard) && StringUtils.isNotEmpty(projectId)){
                //接口查询条件
                Map<String, String> map = new HashMap<String, String>();
                map.put("idCard", idCard);
                map.put("projectId", projectId);
                //接口查询结果
                String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_PERSONMSGURL, map);
                if(result.contains("idCard")){
                    result = result.replaceAll("Work","work").replaceAll("Group","group").replaceAll("null","\"\"");
                }
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                workerDetail = (WorkerDetail)net.sf.json.JSONObject.toBean(jsonObject, WorkerDetail.class);
                if(null != workerDetail){
                    WorkerInfoOut worker = workerDetail.getResolve();
                    worker.setProjectName(projectName);
                    // 获取年龄
                    String getIdCard = worker.getIdCard();
                    if(getIdCard.length() > 15){
                        Map<String, Object> mapCard = IDCardUtils.getCarInfo(getIdCard);
                        age = (Integer) mapCard.get("age");
                    }else{
                        Map<String, Object> mapCard = IDCardUtils.getCarInfo15W(getIdCard);
                        age = (Integer) mapCard.get("age");
                    }
                    // 创建时间
                    createDate = DateUtils.dateStrChangeToTime(worker.getCreatedAt());
                    // 有效期
                    String effectiveTimeSection = worker.getValidDay();
                    if(StringUtils.isNotEmpty(effectiveTimeSection)){
                        String[] timeArr = effectiveTimeSection.split("-");
                        String startTime = timeArr[0].replaceAll("\\.","-");
                        String endTime = timeArr[1].replaceAll("\\.","-");
                        Map dateMap = DateUtils.getApartTime(startTime,endTime);
                        if(null != dateMap){
                            effectiveTime = (Integer) dateMap.get("YEAR");
                        }
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取人员信息->>getUsers->>Exception " + e.getMessage());
        }
        request.setAttribute("workerInfo",workerDetail.getResolve());
        request.setAttribute("age",age);
        request.setAttribute("createDate",createDate);
        request.setAttribute("effectiveTime",effectiveTime + 1);
        return "/wo/workerInfo/workerInfoDesc";
    }


    /**
     * 获取姓名下拉表数据
     * @param response
     */
    @RequestMapping(value = "/getWorkerCombo.do")
    public void getWorkerCombo(HttpServletResponse response,String prId) {
        logger.info("加载农名工人员信息列表-->>开始");
        try {
            //获取项目信息
            Project project = iProjectService.selectById(prId);
            JSONArray array = new JSONArray();
            //将项目id和项目名称存入projectMap
            String prName = "";
            if (null != project) {
                prName = project.getPrName();
            }
            if (StringUtils.isNotEmpty(prId)) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageNumber", String.valueOf(1));
                map.put("pageSize", String.valueOf(Integer.MAX_VALUE));
                map.put("projectIds", prId);
                String result = connToserver_HttpClientClose.sendPostRequest(Const.WORKER_PERSONPAGEURL, map);
                if(result.contains("idCard")){
                    result = result.replaceAll("Work","work").replaceAll("Group","group").replaceAll("null","\"\"");
                }
                //对象中存在集合的需要通过map注明集合的类型，否则会报错
                Map classMap = new HashMap();
                classMap.put("persons",WorkerInfoOut.class);
                net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(result);
                GetWorkerListOut workers = (GetWorkerListOut)net.sf.json.JSONObject.toBean(jsonObject, GetWorkerListOut.class,classMap);
                //劳务人员信息集合
                List<WorkerInfoOut> workerList = workers.getPersonObj().getPersons();
                repairInfoMap = new HashMap<>();
                for(WorkerInfoOut worker : workerList){
                    Map<String,String> repairMap = new HashMap<>();
                    JSONObject jsonObj = new JSONObject();
                    String id = worker.getId();
                    String name = worker.getName();
                    String projectId = worker.getProjectId();
                    jsonObj.put("id",id);
                    jsonObj.put("name",name);
                    array.put(jsonObj);
                    // 将部分数据存在成员变量repairInfoMap中，
                    // 方便前端补卡姓名下拉中请求getWorkerMap.do，点选加载对应数据
                    repairMap.put("id",id);
                    repairMap.put("name",name);
                    repairMap.put("idCard",worker.getIdCard());
                    repairMap.put("sex",worker.getSex());
                    repairMap.put("groupName",worker.getGroup().getName());
                    repairMap.put("projectId",projectId);
                    repairMap.put("projectName",prName);
                    repairMap.put("userId",UserUtils.getCurrentUser().getUsId());
                    repairMap.put("userName",UserUtils.getCurrentUser().getLoginName());
                    repairInfoMap.put(id,repairMap);
                }
            }
            ResManager.getJsonOut(response).print(array);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取人员信息-->>Exception " + e.getMessage());
        }
    }

    /**
     * 前端补卡人员下拉点选，根据人员主键获取repairInfoMap中对应的数据，
     * 自动补入其他输入框
     * @param id
     * @param response
     */
    @RequestMapping(value = "/getWorkerMap.do")
    public void getWorkerMap(String id,HttpServletResponse response){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(StringUtils.isNotEmpty(id)){
            Map<String,String> map = repairInfoMap.get(id);
            map.put("entryDate",sdf.format(new Date()));
            JSONObject jsonObj = new JSONObject(map);
            ResManager.getJsonOut(response).print(jsonObj);
        }
    }

}
